<!-- InventoryOperation.vue 独立出入库操作组件 -->
<template>
  <el-card class="operation-card">
    <div slot="header" class="clearfix">
      <span>出入库操作</span>
      <div style="float: right;">
        <el-button
          type="primary"
          size="small"
          @click="showAddCategoryDialog(null)">
          添加根分类
        </el-button>
      </div>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading-text">加载分类数据中...</div>

    <!-- 顶级分类标签页 -->
    <div v-else>
      <!-- 标签页导航 -->
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="topCategory in topCategories"
          :key="topCategory.id"
          :label="topCategory.name"
          :name="topCategory.id">
        </el-tab-pane>
      </el-tabs>

      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="在当前分类中搜索分类名称"
          clearable
          @clear="resetSearch"
          @input="handleSearch">
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
      </div>

      <!-- 分类操作表格 -->
      <div class="table-container" ref="tableContainer">
        <el-table
          :data="filteredCategoryTree"
          row-key="id"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :default-expand-all="isExpanded"
          border
          style="width: 100%;"
          class="inventory-table"
          :height="tableHeight">

          <!-- 分类名称列（带层级缩进） -->
          <el-table-column
            prop="name"
            label="分类名称"
            width="400"
            fixed="left">
            <template slot-scope="{ row }">
              <div
                :style="{
        'padding-left': (row.level * 15) + 'px',
        'white-space': 'normal'
      }"
                class="category-name">
                <i :class="row.children && row.children.length > 0 ? 'el-icon-folder' : 'el-icon-document'"></i>
                {{ row.name }}
              </div>
            </template>
          </el-table-column>

          <!-- 新增字段列 -->
          <el-table-column prop="specs" label="规格" width="100" show-overflow-tooltip></el-table-column>
          <el-table-column prop="unit" label="单位" width="80"></el-table-column>
          <!-- 当前库存列 -->
          <el-table-column label="当前库存" width="120" >
            <template slot-scope="{ row }">
              {{ row.surplusCount || 0 }}
            </template>
          </el-table-column>
          <!-- 出库操作列 fixed="right" -->
          <el-table-column label="出库数量" width="180" >
            <template slot-scope="{ row }">
              <el-input-number
                v-model="row.outQuantity"
                :min="0"
                :step="1"
                size="small"
                @change="val => handleQuantityChange(row, 'out', val)">
              </el-input-number>
            </template>
          </el-table-column>

          <!-- 入库操作列 -->
          <el-table-column label="入库数量" width="180" >
            <template slot-scope="{ row }">
              <el-input-number
                v-model="row.inQuantity"
                :min="0"
                :step="1"
                size="small"
                @change="val => handleQuantityChange(row, 'in', val)">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="batchNumber" label="批号" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="effectiveDate" label="有效期" width="150">
            <template slot-scope="{ row }">
              {{ formatDate(row.effectiveDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="100">
            <template slot-scope="{ row }">
              {{ row.price ? '¥' + row.price : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="certificateNumber" label="注册证号" width="150" show-overflow-tooltip></el-table-column>
          <el-table-column prop="license" label="生产许可" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="manufacturer" label="生产厂家" width="150" show-overflow-tooltip></el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="mini"
                @click="showAddCategoryDialog(row)">
                添加子类
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="showEditCategoryDialog(row)">
                编辑
              </el-button>
              <el-button
                type="text"
                size="mini"
                style="color: #F56C6C"
                @click="deleteCategory(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 操作按钮 -->
    <div class="operation-footer">
      <el-button
        type="primary"
        @click="submitOperation"
        :disabled="loading">
        提交操作
      </el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      :title="categoryDialogTitle"
      :visible.sync="categoryDialogVisible"
      width="600px"
      :close-on-click-modal="false">
      <el-form :model="currentCategory" label-width="120px" ref="categoryForm">
        <el-form-item label="分类名称" prop="name" required>
          <el-input v-model="currentCategory.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <!-- 修复：仅在添加分类时显示父级分类选择器 -->
        <el-form-item
          label="上级分类"
          v-if="!currentCategory.id && !currentCategory.parentId">
          <el-select
            v-model="currentCategory.parentId"
            placeholder="选择上级分类"
            style="width: 100%">
            <el-option
              v-for="category in topCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id">
            </el-option>
            <el-option label="无（根分类）" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- 仅当不是添加根分类时显示其他字段 -->
        <template v-if="!isAddingRootCategory">
          <el-row :gutter="20">
            <el-col :span="12">
              <!-- 新增：当前库存字段 -->
              <el-form-item label="当前库存" prop="surplusCount">
                <el-input-number
                  v-if="!currentCategory.id"
                  v-model="currentCategory.surplusCount"
                  :min="0"
                  :step="1"
                  style="width: 100%">
                </el-input-number>
                <el-input
                  v-else
                  v-model="currentCategory.surplusCount"
                  readonly>
                </el-input>
              </el-form-item>

              <el-form-item label="规格" prop="specs">
                <el-input v-model="currentCategory.specs" placeholder="请输入规格"></el-input>
              </el-form-item>

              <el-form-item label="单位" prop="unit">
                <el-input v-model="currentCategory.unit" placeholder="请输入单位"></el-input>
              </el-form-item>

              <el-form-item label="单价" prop="price">
                <el-input-number
                  v-model="currentCategory.price"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  style="width: 100%">
                </el-input-number>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="批号" prop="batchNumber">
                <el-input v-model="currentCategory.batchNumber" placeholder="请输入批号"></el-input>
              </el-form-item>

              <el-form-item label="有效期" prop="effectiveDate">
                <el-date-picker
                  v-model="currentCategory.effectiveDate"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="注册证号" prop="certificateNumber">
                <el-input v-model="currentCategory.certificateNumber" placeholder="请输入注册证号"></el-input>
              </el-form-item>

              <el-form-item label="生产许可" prop="license">
                <el-input v-model="currentCategory.license" placeholder="请输入生产许可"></el-input>
              </el-form-item>

              <el-form-item label="生产厂家" prop="manufacturer">
                <el-input v-model="currentCategory.manufacturer" placeholder="请输入生产厂家"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="上级分类" v-if="!currentCategory.parentId">
            <el-select
              v-model="currentCategory.parentId"
              placeholder="选择上级分类"
              style="width: 100%">
              <el-option
                v-for="category in topCategories"
                :key="category.id"
                :label="category.name"
                :value="category.id">
              </el-option>
              <el-option label="无（根分类）" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="categoryDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveCategory">保 存</el-button>
  </span>
    </el-dialog>
  </el-card>
</template>

<script>
import categoryApi from '@/api/inventory/category'; // 导入分类API

export default {
  data() {
    return {
      isAddingRootCategory: false, // 新增状态标记
      loading: true,              // 数据加载状态
      rawCategoryData: [],        // 原始分类数据
      processedCategories: [],    // 处理后的分类数据（含操作字段）
      topCategories: [],          // 顶级分类（parentId为0）
      activeTab: null,            // 当前激活的标签页
      currentCategoryTree: [],    // 当前选中的分类树
      filteredCategoryTree: [],   // 过滤后的分类树（搜索用）
      tableHeight: 500,           // 表格初始高度
      searchKeyword: '',          // 搜索关键词
      isExpanded: true,           // 是否展开所有节点
      originalTreeData: [],       // 原始树数据（用于搜索）

      // 分类管理相关状态
      categoryDialogVisible: false, // 分类对话框显示状态
      categoryDialogTitle: '添加分类', // 分类对话框标题
      currentCategory: {           // 当前编辑的分类
        id: null,
        name: '',
        specs: '',
        unit: '',
        price: 0,
        batchNumber: '',
        effectiveDate: null,
        certificateNumber: '',
        license: '',
        manufacturer: '',
        parentId: 0
      }
    };
  },
  mounted() {
    this.loadCategoryData();
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight);
  },
  methods: {
    // 计算表格高度
    calculateTableHeight() {
      if (this.$refs.tableContainer) {
        const containerRect = this.$refs.tableContainer.getBoundingClientRect();
        const windowHeight = window.innerHeight;
        const containerTop = containerRect.top;

        // 增大可用高度：窗口高度 - 容器顶部位置 - 操作按钮高度
        const availableHeight = windowHeight - containerTop - 100; // 100为底部按钮区域高度

        // 设置最小高度和最大高度
        const minHeight = 400;
        const maxHeight = 1000;

        // 确保高度在合理范围内
        this.tableHeight = Math.max(minHeight, Math.min(availableHeight, maxHeight));
      }
    },

    // 处理顶级分类
    processTopCategories() {
      // 找出所有parentId为0的顶级分类
      this.topCategories = this.processedCategories.filter(cat => cat.parentId === 0);

      // 如果有顶级分类，设置默认激活第一个
      if (this.topCategories.length > 0) {
        this.activeTab = this.topCategories[0].id;
        this.updateCurrentCategoryTree();
      }
    },

    // 更新当前分类树
    updateCurrentCategoryTree() {
      if (!this.activeTab && this.topCategories.length > 0) {
        this.activeTab = this.topCategories[0].id;
      }

      if (!this.activeTab) return;

      // 找到当前激活的顶级分类
      const currentTopCategory = this.topCategories.find(cat => cat.id === this.activeTab);

      if (currentTopCategory) {
        // 获取该顶级分类及其所有子分类
        this.currentCategoryTree = [currentTopCategory];
        // 保存原始树数据用于搜索
        this.originalTreeData = JSON.parse(JSON.stringify(this.currentCategoryTree));
        // 初始化过滤后的树
        this.filteredCategoryTree = [...this.currentCategoryTree];
      }
    },
    // 标签页切换事件
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.updateCurrentCategoryTree();
      // 重置搜索
      this.searchKeyword = '';
      this.isExpanded = true;

      // 更新表格高度
      this.$nextTick(() => {
        this.calculateTableHeight();
      });
    },

    // 处理搜索 - 修复搜索功能
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.filteredCategoryTree = [...this.originalTreeData];
        this.isExpanded = true;
        return;
      }

      const keyword = this.searchKeyword.toLowerCase().trim();

      // 深度优先搜索函数
      const filterTree = (nodes) => {
        const result = [];

        for (const node of nodes) {
          // 检查当前节点是否匹配
          const isMatch = node.name.toLowerCase().includes(keyword);

          // 如果有子节点，递归搜索
          let matchedChildren = [];
          if (node.children && node.children.length > 0) {
            matchedChildren = filterTree(node.children);
          }

          // 如果当前节点匹配或子节点有匹配，则保留该节点
          if (isMatch || matchedChildren.length > 0) {
            const newNode = {
              ...node,
              children: matchedChildren
            };
            result.push(newNode);
          }
        }

        return result;
      };

      // 应用搜索过滤
      this.filteredCategoryTree = filterTree(JSON.parse(JSON.stringify(this.originalTreeData)));
      // 搜索时自动展开所有节点
      this.isExpanded = true;
    },

    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.filteredCategoryTree = [...this.originalTreeData];
      this.isExpanded = true;
    },

    // 加载分类数据
// 加载分类数据 (关键修复)
    async loadCategoryData(keepCurrentTab = false) {
      this.loading = true;
      const currentTab = this.activeTab;

      try {
        const res = await categoryApi.getCategoryTree();
        console.log('API返回数据:', res); // 调试日志

        // 修复1: 正确获取data字段中的数据
        this.rawCategoryData = res.data || []; // 确保获取的是data数组

        this.processCategories();

        // 处理顶级分类
        this.topCategories = this.processedCategories.filter(cat => cat.parentId === "0"); // 修复2: 使用字符串"0"匹配

        // 恢复之前激活的标签页
        if (keepCurrentTab && currentTab) {
          const tabExists = this.topCategories.some(cat => cat.id === currentTab);
          if (tabExists) {
            this.activeTab = currentTab;
          } else if (this.topCategories.length > 0) {
            this.activeTab = this.topCategories[0].id;
          }
        } else if (this.topCategories.length > 0) {
          this.activeTab = this.topCategories[0].id;
        }

        // 更新当前分类树
        this.updateCurrentCategoryTree();

        // 数据加载完成后计算表格高度
        this.$nextTick(() => {
          this.calculateTableHeight();
        });

        console.log('处理后的数据:', {
          raw: this.rawCategoryData,
          processed: this.processedCategories,
          top: this.topCategories,
          currentTree: this.currentCategoryTree
        }); // 调试日志
      } catch (error) {
        console.error('加载分类数据失败:', error);
        this.$message.error('分类数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    // 处理分类数据结构（添加操作字段）
    processCategories() {
      const addOperationFields = (nodes, level = 0) => {
        return nodes.map(node => {
          // 确保children存在并处理
          const children = node.children && node.children.length > 0 ?
            addOperationFields(node.children, level + 1) : [];

          return {
            ...node,
            level,
            outQuantity: 0,
            inQuantity: 0,
            children
          };
        });
      };

      // 确保从原始数据开始处理
      this.processedCategories = addOperationFields(this.rawCategoryData);
    },
    // 格式化日期
    formatDate(dateValue) {
      if (!dateValue) return '-';
      // 如果是时间戳（数字）
      if (typeof dateValue === 'number') {
        const date = new Date(dateValue);
        return date.toISOString().split('T')[0];
      }
      // 如果是字符串
      if (typeof dateValue === 'string') {
        // 尝试转换为日期对象
        const dateObj = new Date(dateValue);
        if (!isNaN(dateObj)) {
          return dateObj.toISOString().split('T')[0];
        }
        // 直接截取日期部分（YYYY-MM-DD）
        if (dateValue.length > 10) {
          return dateValue.substr(0, 10);
        }
        return dateValue;
      }
      return dateValue;
    },

    // 处理数量输入变化
    handleQuantityChange(row, type, value) {
      // 新增：库存校验逻辑
      const newSurplus = row.surplusCount + row.inQuantity - row.outQuantity;
      if (newSurplus < 0) {
        this.$message.error(`分类【${row.name}】操作后库存不能小于零`);
        // 重置当前操作数量
        if (type === 'out') {
          row.outQuantity = 0;
        } else {
          row.inQuantity = 0;
        }
      }
    },

    // 提交操作
    async submitOperation() {
      try {
        // 先检查是否有操作数据
        const operations = this.collectOperations();
        if (operations.length === 0) {
          this.$message.warning('请至少选择一个分类进行操作');
          return;
        }

        // 再检查库存是否充足
        const invalidCategories = this.findInvalidCategories(this.processedCategories);
        if (invalidCategories.length > 0) {
          const names = invalidCategories.map(c => `【${c.name}】`).join('、');
          this.$message.error({
            dangerouslyUseHTMLString: true,
            message: `以下分类库存不足：<br>${names}<br>请检查后再提交`,
            duration: 5000
          });
          return;
        }

        // 执行提交操作
        await categoryApi.updateInventoryOperations(operations);
        this.$message.success('操作提交成功');
        await this.loadCategoryData(true); // 保留当前标签页
        this.resetForm();
      } catch (error) {
        this.$message.error('操作提交失败: ' + (error.response?.data?.message || error.message));
      }
    },

    // 新增：递归查找所有无效分类
    findInvalidCategories(nodes) {
      let result = [];
      nodes.forEach(node => {
        const currentSurplus = node.surplusCount + node.inQuantity - node.outQuantity;
        if (currentSurplus < 0) {
          result.push({ name: node.name });
        }
        if (node.children?.length > 0) {
          result = result.concat(this.findInvalidCategories(node.children));
        }
      });
      return result;
    },

    // 收集有效操作数据
    collectOperations() {
      const traverse = (nodes) => {
        let operations = [];
        nodes.forEach(node => {
          if (node.outQuantity > 0 || node.inQuantity > 0) {
            operations.push({
              categoryId: node.id,
              outQuantity: node.outQuantity,
              inQuantity: node.inQuantity
            });
          }
          if (node.children?.length > 0) {
            operations = operations.concat(traverse(node.children));
          }
        });
        return operations;
      };
      return traverse(this.processedCategories);
    },

    // 重置表单
    resetForm() {
      const resetNodes = (nodes) => {
        nodes.forEach(node => {
          node.outQuantity = 0;
          node.inQuantity = 0;
          if (node.children) resetNodes(node.children);
        });
      };
      resetNodes(this.processedCategories);
    },

    // 显示添加分类对话框
    showAddCategoryDialog(parent) {
      // 设置是否是添加根分类
      this.isAddingRootCategory = !parent;
      this.categoryDialogTitle = parent ? `添加子分类 (${parent.name})` : '添加根分类';
      this.currentCategory = {
        id: null,
        name: '',
        specs: '',
        unit: '',
        price: 0,
        batchNumber: '',
        effectiveDate: null,
        certificateNumber: '',
        license: '',
        manufacturer: '',
        surplusCount: 0, // 初始化库存为0
        parentId: parent ? parent.id : 0
      };
      this.categoryDialogVisible = true;
    },

    // 显示编辑分类对话框
    showEditCategoryDialog(category) {
      this.categoryDialogTitle = `编辑分类 (${category.name})`;
      this.currentCategory = {
        id: category.id,
        name: category.name,
        specs: category.specs || '',
        unit: category.unit || '',
        price: category.price || 0,
        surplusCount: category.surplusCount || 0, // 保留现有库存值
        batchNumber: category.batchNumber || '',
        effectiveDate: category.effectiveDate || null,
        certificateNumber: category.certificateNumber || '',
        license: category.license || '',
        manufacturer: category.manufacturer || '',
        parentId: category.parentId || 0 // 保留原始父级ID
      };
      this.categoryDialogVisible = true;
    },

    // 保存分类
    async saveCategory() {
      try {
        if (!this.currentCategory.name) {
          this.$message.warning('分类名称不能为空');
          return;
        }

        const params = {
          ...this.currentCategory,
          // 编辑时不更新父级ID
          parentId: this.currentCategory.id
            ? undefined // 编辑时排除parentId
            : this.currentCategory.parentId
        };

        if (params.id) {
          // 更新分类
          await categoryApi.updateCategory(params.id, params);
          this.$message.success('分类更新成功');
        } else {
          // 创建新分类
          await categoryApi.createCategory(params);
          this.$message.success('分类创建成功');
        }

        this.categoryDialogVisible = false;
        await this.loadCategoryData(true);
      } catch (error) {
        this.$message.error('保存失败: ' + (error.response?.data?.message || error.message));
      }
    },

    // 删除分类
    async deleteCategory(category) {
      try {
        await this.$confirm(`确定删除分类 "${category.name}" 吗？`, '提示', {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消'
        });

        await categoryApi.deleteCategory(category.id);
        this.$message.success('分类删除成功');
        await this.loadCategoryData(true);
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + (error.response?.data?.message || error.message));
        }
      }
    }
  }
};
</script>

<style scoped>
.loading-text {
  padding: 20px;
  text-align: center;
  color: #909399;
}

.operation-card {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px); /* 使用全屏高度 */
}

/* 修改按钮区域样式 */
.operation-footer {
  margin-top: 15px;
  text-align: right;
  padding: 10px 0;
  background: #fff;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

/* 分类名称样式 */
.category-name {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.category-name i {
  margin-right: 5px;
  color: #409EFF;
}

/* 表格容器 - 增大高度 */
.table-container {
  flex: 1; /* 占据剩余空间 */
  overflow: auto; /* 添加滚动 */
  position: relative;
  min-height: 500px; /* 最小高度保证 */
}

/* 表格滚动支持 */
.inventory-table {
  width: 100%;
  /* 移除 height 属性 */
}

/* 固定滚动条位置 */
.inventory-table .el-table__body-wrapper {
  height: calc(100% - 40px); /* 减去表头高度 */
  overflow: auto;
}

/* 优化滚动条体验 */
.inventory-table ::-webkit-scrollbar {
  width: 10px; /* 增大滚动条宽度 */
  height: 10px;
}

.inventory-table ::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 4px;
}

.inventory-table ::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 5px;
}

.inventory-table ::-webkit-scrollbar-thumb:hover {
  background: #909399;
}


/* 输入框大小调整 */
.inventory-table .el-input-number--small {
  width: 120px;
}

/* 标签页样式 */
.el-tabs {
  margin-bottom: 15px;
}

/* 搜索容器 */
.search-container {
  margin-bottom: 15px;
  max-width: 300px;
}

/* 操作按钮样式 */
.el-button--text {
  padding: 5px;
  margin-left: 0;
  margin-right: 5px;
}

/* 对话框表单样式 */
.el-form-item {
  margin-bottom: 18px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .operation-card {
    height: auto;
  }

  .table-container {
    min-height: 300px;
  }
}
.inventory-table .el-table__row {
  height: auto !important; /* 自动高度 */
}

.inventory-table .el-table__body td {
  padding: 8px 0; /* 增加单元格内边距 */
}

.category-name {
  line-height: 1.5; /* 增加行高 */
  padding: 4px 0; /* 名称区域增加内边距 */
}
</style>
